function savemat2h5(h5file, X, Y, chunksz)

if ndims(X) == 4
    len = size(X, 4);
    to4d = @(x, pp) x(:, :, :, pp);
else
    len = size(X, 3);
    to4d = @(x, pp) permute(shiftdim(x(:, :, pp), -1), [2 3 1 4]);
end

fprintf('\tConverting mat to h5 file ...\n');
pp = 0;
curr_dat_sz = 0;
while true
    pp = pp(end)+1 : pp(end)+chunksz;
    if pp(end) > len
        break;
    end
    
    xx = to4d(X, pp);
    yy = to4d(Y, pp);
    
    totalct = curr_dat_sz(end);
    startloc.dat = [1, 1, 1, totalct+1];
    startloc.lab = [1, 1, 1, totalct+1];
    curr_dat_sz = store2hdf5(h5file, xx, yy, pp(1) == 1, startloc, chunksz);
end
fprintf('\tDone!\n\n');
% h5disp(h5file);
